﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static ILog log = LogManager.GetLogger(typeof(MainWindow));
        private String loginUrl = ConfigurationManager.AppSettings["loginUrl"];

        public MainWindow()
        {
            log.Debug("MainWindow Init.");
            InitializeComponent();
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            log.Debug("Window_Loaded");

            // 获取JSESSIONID
            try {

                await getSessionId();

            } catch (Exception ex){ 
                log.Error("Window_Loaded", ex);
            }
        }

        private async Task<String> getSessionId() {
            log.Info("getSessionId start.");
            String sessionId = String.Empty;

            try
            {
                using (var client = new HttpClient())
                {
                    log.Info("Request Url:" + loginUrl);
                    using (var request = new HttpRequestMessage(HttpMethod.Get, loginUrl))
                    {
                        using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
                        {
                            IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == "Set-Cookie").Value;
                            log.Info(JsonConvert.SerializeObject(cookies));
                            // ["JSESSIONID=63E3934F029DF7C6F33043935DE16190; Path=/Eis_UI; HttpOnly"] 
                            String[] stringArray = cookies.First().Split(';');

                            log.Info("cookie:"+ stringArray[0]);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("getSessionId Exception：", ex);
            }

            log.Info("getSessionId end.");
            return sessionId;
        }
    }
}
